package com.itic.system.user.user.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itic.appbase.framework.Base.BaseCode;
import com.itic.appbase.framework.type.*;
import com.itic.system.carrage.template.service.CarrageTemplateService;
import com.itic.system.user.attention.service.UserAttentionService;
import com.itic.system.user.balanceLog.persistence.model.UserBalanceLog;
import com.itic.system.user.balanceLog.service.UserBalanceLogService;
import com.itic.system.user.withdraw.service.UserWithDrawRecordService;
import com.itic.system.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.system.user.user.persistence.dao.HppUserDao;
import com.itic.system.user.user.persistence.model.HppUser;
import com.itic.system.user.user.persistence.model.HppUserExample;
import com.itic.system.user.user.persistence.model.HppUserExample.Criteria;
import com.itic.appbase.framework.utils.WxUtils;

@Service
@Transactional
public class HppUserService extends CrudService<HppUserDao, HppUser, HppUserExample> {
	@Autowired
	private HppUserDao hppUserDao;
	@Autowired
	private UserBalanceLogService userBalanceLogService;
	@Autowired
	private UserWithDrawRecordService userWithDrawRecordService;
	@Autowired
	private UserAttentionService userAttentionService;
	@Autowired
	private CarrageTemplateService carrageTemplateService;



	/**
	 * 个人入住
	 * @param vos
	 * @return
	 */
	public String psetEdit(PersonSetInVo vos){
		String result = FAILED;
		String userId = vos.getUserId();
		HppUser user = this.get(userId);
		if(user != null){
			user.setNickName(vos.getName());
			user.setEmail(vos.getMail());
			user.setIdentity(vos.getIdentity());
			user.setIdentityType(vos.getIdentityType());
			user.setPhone(vos.getPhone());

			user.setIdentityExpireTimeE(vos.getIdExpireEtime());
			user.setIdentityExpireTimeS(vos.getIdExpireStime());
			user.setIdentityImgB(vos.getIdbPhoto());
			user.setIdentityImgF(vos.getIdfPhoto());
			user.setHeadImg(vos.getIdHeamimg());

			user.setLogo(vos.getLogo());
			user.setStoreName(vos.getStoreName());

			user.setSendAuth(DBConst.TRUE);
			user.setGoodsAuth(DBConst.FALSE);
			user.setRefundAuth(DBConst.TRUE);
			result = this.edit(user);
		}
		return result;
	}
	/**
	 * 修改用户信息
	 * @param user
	 * @return
	 */
	public String editUserInfo(HppUser user){
		String result = FAILED;
		if(user != null){
			result = this.edit(user);
		}
		return result;
	}

	/**+
	 * 注册新用户
	 * @param code
	 * @param phone
	 * @param appId
	 * @param appSecret
	 * @return
	 */
	public String regNewUser(String code, String phone,String appId,String appSecret) {
		HppUser user = new HppUser();
		Map<String,String> map = WxUtils.getWXuserBycode(code,appId,appSecret);
		String openId = map.get("openId");
		String nickname = map.get("nickname");
		String headimgurl = map.get("headimgurl");
		user.setHeadImg(headimgurl);
		user.setOpenId(openId);
		user.setPhone(phone);
		user.setNickName(nickname);
		user.setState(UserStateType.fail.getType());
		String result = this.add(user);
		return result;
	}

	/**
	 * 修改密码
	 * @param phone
	 * @param newPwd
	 * @return
	 */
	public Integer updatePwd(String phone, String newPwd) {
		Integer result = 0;
		//根据手机号查询用户
		HppUser hppUser = this.getUserByPhone(phone);
		hppUser.setPassWord(newPwd);
		result = this.hppUserDao.updateByPrimaryKey(hppUser);
		return result;
	}
	/**
	 * 根据手机号查询用户信息
	 * @param phone
	 * @return
	 */
	public HppUser getUserByPhone(String phone){
		HppUser hppUser = this.hppUserDao.getUserByPhone(phone);
		return hppUser;
	}

	/**
	 * 账号密码登陆
	 * @param phone
	 * @param pwd
	 * @return
	 */
	public String login(String phone,String pwd){
		String result = FAILED;
		HppUserExample example = new HppUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andPhoneEqualTo(phone);
		criteria.andPassWordEqualTo(pwd);
		List<HppUser> list = this.hppUserDao.selectByExample(example);
		if(list.size()>0){
			result = SUCCESS;
		}
		return result;
	}
	
	public UserVo chgToUserVo(HppUser user){
		UserVo vo = new UserVo();
		if(user != null){
			vo.setAboutMe(user.getAboutMe());
			vo.setCreateTime(user.getCreateTime());
			vo.setEmail(user.getEmail());
			vo.setGoodsAuth(user.getGoodsAuth());
			vo.setHeadImg(user.getHeadImg());
			vo.setId(user.getId());
			vo.setIdentity(user.getIdentity());
			vo.setIdentityExpireTimeE(user.getIdentityExpireTimeE());
			vo.setIdentityExpireTimeS(user.getIdentityExpireTimeS());
			vo.setIdentityImgB(user.getIdentityImgB());
			vo.setIdentityImgF(user.getIdentityImgF());
			vo.setIdentityType(user.getIdentityType());
			vo.setLogo(user.getLogo());
			vo.setMoney(user.getMoney());
			vo.setNickName(user.getNickName());
			vo.setOpenId(user.getOpenId());
			vo.setPhone(user.getPhone());
			vo.setQrCode(user.getQrCode());
			vo.setRefundAuth(user.getRefundAuth());
			vo.setSendAuth(user.getSendAuth());
			vo.setState(user.getState());
			vo.setStoreName(user.getStoreName());
		}
		return vo;
	}


	public UserVo getUser(String openId) {
		UserVo vo = null;
		//根据Openid查询用户信息
		HppUser user = this.hppUserDao.getHppUserByOpenId(openId);
		if (user!=null) {
			vo = this.chgToUserVo(user);
		}
		return vo;
	}

	/**
	 * 认证用户信息
	 * 
	 * @param openId
	 * @param phone
	 * @param nickName
	 * @param avatarUrl
	 * @return
	 */
	public HppUser authUser(String openId, String phone, String nickName, String avatarUrl) {
		// 查询用户是否认证过
		String result = SUCCESS;
		// 通过OpendId查询用户
		HppUser user = this.hppUserDao.getHppUserByOpenId(openId);
		// 判断用户是否存在 若不存在添加一条用户信息 否则 更新用户的认证信息
		if (user == null){
			user = this.addUser(openId, phone, nickName, avatarUrl);
			//初始化全国包邮模板
			this.carrageTemplateService.createDefaultTemplate(user.getId());
		}else
			result = this.editUser(user, phone, nickName, avatarUrl);
		return user;
	}

	/**
	 * 添加hpp用户
	 * 
	 * @param openId
	 * @param phone
	 * @param nickName
	 * @param headImage
	 * @return
	 */
	public HppUser addUser(String openId, String phone, String nickName, String headImage) {
		HppUser hppUser = new HppUser();
		hppUser.setHeadImg(headImage);
		hppUser.setOpenId(openId);
		hppUser.setNickName(nickName);
		hppUser.setPhone(phone);
		String result = this.add(hppUser);
		if(SUCCESS.equals(result))
			return hppUser;
		else
			return null;
	}

	public String editUser(HppUser user, String phone, String nickName, String headImage) {
		user.setPhone(phone);
		user.setNickName(nickName);
		user.setHeadImg(headImage);
		String result = this.edit(user);
		return result;
	}

	public String  getUserPhoneByOpenId(String openId){
		HppUser hppUser = this.hppUserDao.getHppUserByOpenId(openId);
		if(hppUser !=null)
			return hppUser.getPhone();
		else
			return  "";

	}

	/**
	 * 个人中心Vo
	 * @param userId
	 * @return
	 */
	public Map<String,Object> personalCenter(String userId){
		Map<String, Object> resultMap = new HashMap<>();
		HppUser hppUser = this.get(userId);
		if(hppUser!=null){
			PersonalCenterVo personalCenterVo = new PersonalCenterVo();
			personalCenterVo.setUserId(hppUser.getId());
			int fansCount = this.userAttentionService.findFanCountByUserId(userId);
			personalCenterVo.setFansCount(fansCount);
			int followCount = this.userAttentionService.findAttentionCountByUserId(userId);
			personalCenterVo.setFollowCount(followCount);
			personalCenterVo.setHeadImge(hppUser.getHeadImg());
			double money = hppUser.getMoney()==null?0:hppUser.getMoney();
			personalCenterVo.setMoney(money);
			personalCenterVo.setNickName(hppUser.getNickName());
			resultMap.put(BaseCode.DATA,personalCenterVo);
			resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
			resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
		}else{
			resultMap.put(BaseCode.CODE,BaseCode.HPP_USER_NOT_EXSIT_CODE);
			resultMap.put(BaseCode.MSG,BaseCode.HPP_USER_NOT_EXSIT_MSG);
		}
		return resultMap;
	}

	/**
	 * 将HPPuser 转换成CollageHeadInfoVo
	 * @param hppUser
	 * @return
	 */
	public CollageHeadInfoVo  getCollageHeadInfoVo(HppUser hppUser){
		CollageHeadInfoVo collageHeadInfoVo = new CollageHeadInfoVo();
		collageHeadInfoVo.setNickName(hppUser.getNickName());
		collageHeadInfoVo.setHeadImage(hppUser.getHeadImg());
		collageHeadInfoVo.setPhone(hppUser.getPhone());
		collageHeadInfoVo.setQrCode(hppUser.getQrCode());
		return collageHeadInfoVo;
	}

	/**
	 * 操作用户的余额  加减
	 * @param userId
	 * @param money
	 * @param operateType
	 * @return
	 */
	public String operateUserMoney(String userId, double money, OperateType operateType,FlowType flowType , FlowMethod flowMethod ,String orderNo, FlowSource flowSource , String sourceUserId){
		HppUser hppUser  = this.get(userId);
		String result = SUCCESS;
		if(hppUser!=null){
			double originMoney = hppUser.getMoney()==null?0:hppUser.getMoney();
			double resultMoney = this.calUserMoney(originMoney,operateType,money);
			if(resultMoney <0)
				result = FAILED;
			if(SUCCESS.equals(result)){
				hppUser.setMoney(resultMoney);
				result = this.edit(hppUser);
				//添加收入支出明细
				switch (flowType){
					case InCome:
						this.userBalanceLogService.addIncome(userId,money,flowType,flowMethod,operateType,orderNo,flowSource,sourceUserId);
						break;
					case ExPend:
						this.addExPend(hppUser,money,flowType,flowMethod,operateType);
						break;
				}
			}
		}else
			result=FAILED;
		return result;
	}

	private  double calUserMoney(double originMoney,OperateType operateType,double operateMoney){
		double resultMoney =0;
		switch (operateType){
			case add:
				resultMoney = originMoney + operateMoney;
				break;
			case sub:
				resultMoney = originMoney - operateMoney;
				break;
		}
		return resultMoney;
	}

	/**
	 * 根据userId获取用户信息
	 * @param userId
	 * @return
	 */
	public UserVo getUserInfo(String userId) {
		UserVo vo = null;
		//根据Openid查询用户信息
		HppUser user = this.get(userId);
		if (user!=null) {
			vo = this.chgToUserVo(user);
		}
		return vo;
	}

	public void addExPend(HppUser user, double money, FlowType flowType , FlowMethod flowMethod , OperateType operateType){
		//添加余额支出记录
		UserBalanceLog userBalanceLog = this.userBalanceLogService.addExPend(user.getId(),money,flowType,flowMethod,operateType);
		if(userBalanceLog!=null){
			//各种支出各种记录
			switch (flowMethod){
				case WithDraw:
					this.userWithDrawRecordService.applyWithDrawRecord(user,money,userBalanceLog.getId());
					break;
			}
		}
	}

}